package blog

import (
	"github.com/astaxie/beego/orm"
	"time"
)

// 首页轮播
type Carousel struct {
	Id      int
	Url     string `orm:"size(128);index"`
	Href    string `orm:"size(128);index"`
	Enable  bool
	StartAt time.Time `orm:"type(datetime)"`
	EndAt   time.Time `orm:"type(datetime)"`
	Remark  string    `orm:"size(255)"`
}

func (o *Carousel) TableName() string {
	return "blog_carousel"
}

func CreateCarousel(url, href string, startAt, endAt time.Time, remark string) error {
	carousel := Carousel{Url: url, Href: href, StartAt: startAt, EndAt: endAt, Enable: true, Remark: remark}
	_, err := orm.NewOrm().Insert(&carousel)
	return err
}

func GetAllEnableCarousel() (all []Carousel, err error) {
	_, err = orm.NewOrm().QueryTable(new(Carousel)).Filter("enable", true).Filter("start_at__lte", time.Now()).Filter("end_at__gte", time.Now()).All(&all)
	return
}

func GetCarouselPaginator(limit, page int) (all []Carousel, total int64, err error) {
	if limit == 0 {
		limit = 10
	}
	if page == 0 {
		page = 1
	}
	total, _ = orm.NewOrm().QueryTable(new(Carousel)).Count()
	_, err = orm.NewOrm().QueryTable(new(Carousel)).Offset((page - 1) * limit).Limit(limit).All(&all)
	return
}

func ChangeCarouselEnable(id int, enable bool) error {
	carousel := Carousel{Id: id}
	err := orm.NewOrm().Read(&carousel)
	if err != nil {
		return err
	}
	carousel.Enable = enable
	_, err = orm.NewOrm().Update(&carousel)
	return err
}

func RemoveCarouseById(id int) error {
	_, err := orm.NewOrm().QueryTable(new(Carousel)).Filter("id", id).Delete()
	return err
}
